# -*- coding:utf-8 -*-
from flask import Flask,jsonify,request
from functools import wraps
from flask import make_response
from log_kafka import blemessage,bluemessage,wifimessage
#from flask_paginate import Pagination,get_page_parameter
import ast,math,re
import pymysql
import json,time
from datetime import datetime
from log_kafka import sqlconnect
app = Flask(__name__)

def allow_cross_domain(fun):
    @wraps(fun)
    def wrapper_fun(*args, **kwargs):
        rst = make_response(fun(*args, **kwargs))
        rst.headers['Access-Control-Allow-Origin'] = '*'
        rst.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'
        allow_headers = "Referer,Accept,Origin,User-Agent"
        rst.headers['Access-Control-Allow-Headers'] = allow_headers
        return rst
    return wrapper_fun


@app.route('/')
def hello_world():
    return 'Hello World!'
# -------------------Blue------------------------------------
@app.route('/ble',methods=['GET'])
@allow_cross_domain
def ble_info():
    db=sqlconnect.connect()
    cur = db.cursor()
    # get annual sales rank
    sql = "select id,interface,rssi,hop,asset_mac,evtsrc_ip,flags,services,evt_dev_time,asset_type, detail from ble_info"
    try:
        cur.execute(sql)
        ble = cur.fetchall()
        #bleforjson={}
        bleforjson=[]
        for b in ble:
            d={}
            d['id'] = b[0]
            d['interface'] = b[1]
            d['rssi'] = b[2]
            d['hop'] = b[3]
            d['asset_mac'] = b[4]
            if b[4] and blemessage.MAC_To_Conpany(b[4]):
                d['company'] = blemessage.MAC_To_Conpany(b[4])[0]
            else:
                d['company'] = '未知'
            d['evtsrc_ip'] = b[5]
            d['flags'] = b[6]
            #print type(b[7]),b[7]
            if b[7] != None and b[7] != {}:
                d['service'] =ast.literal_eval(b[7])
            else:
                d['service'] = "null"

            d['evt_dev_time'] = str(b[8])
            d['asset_type'] = b[9]
            d['detail'] = b[10]
            bleforjson.append(d)
        #j = json.dumps(bleforjson)
        return jsonify({'bleInfo':bleforjson})
    except:
        import traceback
        traceback.print_exc()
        return jsonify({'tasks':'Error: unable to Ble fetch data'})
    db.close()
@app.route('/blemac',methods=['GET'])
@allow_cross_domain
def select_ble_MAC():
    db = sqlconnect.connect()
    cur =db.cursor()
    sql="select distinct asset_mac from blue_info where interface='Ble';"
    try:
        cur.execute(sql)
        blemac = cur.fetchall()
        aa =[]
        for i in range(0,len(blemac)):
            aa.append(blemac[i][0])
        #print aa
        return jsonify({'blemac':aa})
    except:
        return jsonify({'tasks': 'Error: unable to get BleMAc fetch data'})
    db.close()

@app.route('/deleteble/<int:id>', methods=['POST'])
@allow_cross_domain
def deletebleInfo(id):
    #data = json.loads(request.get_data())
    #print data
    db = sqlconnect.connect()
    cur = db.cursor()
    sql = "delete from ble_info where id = %s;"
    print id
    try:
        cur.execute(sql,[id])
        db.commit()
        return '', 204
    except:
       return jsonify({'tasks': 'Error: unable to delete Blue fetch data'})

    db.close()

@app.route('/mactoserviceble1/<string:mac>', methods=['GET'])
@allow_cross_domain
def mac_to_service1111(mac):
    print mac
    db = sqlconnect.connect()
    #print asset_mac
    #print type(mac.encode('utf-8'))


    cur = db.cursor()

    sql = "select services from ble_info where asset_mac= %s limit 1;"
    try:
        cur.execute(sql,[mac])
        bleservice = cur.fetchone()
        return jsonify({'bleservice':eval(bleservice[0])})
    except:
        return jsonify({'tasks': 'Error: unable to select mac to services data'})

    db.close()

# 蓝牙攻击监测的信息和低功耗蓝牙对应的服务
@app.route('/mactoserviceble/<string:mac>', methods=['GET'])
@allow_cross_domain
def mac_to_service(mac):
    aa = mac.encode('utf-8').split(';')
    device_type = aa[1]
    asset_mac = aa[0]
    db = sqlconnect.connect()
    #print asset_mac
    #print type(mac.encode('utf-8'))
    bleDic = {'associationAttack': '关联攻击',
              'DisassociationAttack': '请求关联攻击',
              'DataReplyAttack': 'QoS数据重放攻击',
              "proberequAttack": '探测请求攻击',
              'authAttackdic': 'Auth攻击',
              'DeauthAttack': 'Deauth攻击',
              'BeaconFloodAttack': 'Beancon泛洪攻击',
              'bleFuzzAttack': 'Fuzz攻击',
              'bleConnectAttack': '连接攻击',
              'bleAdAttack': '广播攻击',
              'Fuzz': 'Fuzz攻击',
              'bleScanAttack': '扫描攻击',
              'airpods': 'airpods攻击',
              'ios_apid':'ios_apid攻击',
              'ios_phone':'ios_phone攻击',
              }
   #print device_type,asset_mac
    if device_type == '低功耗蓝牙':
        cur = db.cursor()
        cur2= db.cursor()

        sql = "select services from blue_info where asset_mac= %s limit 1;"
        sql2 = "select master,slave,scan_time,attack_type from bleAttackScan where slave=%s order by scan_time desc"
        try:
            cur.execute(sql, [asset_mac])
            cur2.execute(sql2, [asset_mac.lower()])
            bleservice = cur.fetchone()
            attackmessage = cur2.fetchall()
            a = []
            for b in attackmessage:
                d = {}
                # d['id'] = b[0]
                d['master'] = b[0].upper()
                d['slave'] = b[1].upper()
                d['time'] = b[2].strftime('%Y-%m-%d %H:%M:%S')
                d['attack_type'] =bleDic[b[3]]
                a.append(d)
            return jsonify({'bleservice':eval(bleservice[0]),'attackmessage':a})
        except:
            return jsonify({'tasks': 'Error: unable to select mac to services data'})
    elif device_type == '经典蓝牙':
        cur = db.cursor()
        sql = "select id, interface, master, scan_time, attack_type from blueAttackScan where master=%s order by scan_time desc;"
        try:
            cur.execute(sql,[asset_mac])
            blueattack = cur.fetchall()
            a = []
            for b in blueattack:
                d = {}
                d['id'] = b[0]
                d['interface'] = b[1]
                d['master'] = b[2]
                d['slave'] = "未知"
                d['time'] = b[3].strftime('%Y-%m-%d %H:%M:%S')
               # print [v for k,v in eval(b[4]).items()][0]
               # print b[4].split(':',1)[1][1:]
                #d['attack_type'] = [v for k,v in eval(b[4]).items()][0].split(':')[1]
                d['attack_type'] = bleDic[b[4]]
                a.append(d)
            return jsonify({'bleservice':'无服务信息','attackmessage': a})
        except:
            return jsonify({'tasks': 'Error: unable to BlueAttack fetch data'})
    db.close()
# 蓝牙信息
@app.route('/blue',methods=['GET'])
@allow_cross_domain
def blue_info():
    db = sqlconnect.connect()
    cur = db.cursor()
    sql = 'select asset_mac, interface, protocols, detail, pro, ports, asset_type, evt_dev_time, status, rssi,hop, flags from (select distinct asset_mac, interface, protocols, detail, pro, ports, asset_type, evt_dev_time, status, rssi,hop, flags from blue_info) as tam order by status desc;'
    try:
        cur.execute(sql)
        blue = cur.fetchall()
        blueforjson = []

        for b in blue:
            d = {}
         #   d['id'] = b[0]
            d['interface'] = b[1]
            d['asset_mac'] = b[0]
            if blemessage.MAC_To_Conpany(b[0]):
                d['company'] = blemessage.MAC_To_Conpany(b[0])[0]
            else:
                d['company'] = '未知'
            #print type(d['company'])
            if b[2] == 'unknown':
                d['protocols'] = 'L2CAP'
            else:
                d['protocols'] = b[2]

            d['detail'] = b[3]
            d['pro'] =b[4]
            if b[5] == 0:
                d['ports'] = '31'
            else:
                d['ports'] = b[5]
            d['asset_type'] = bluemessage.device_type(b[6])
            d['create_time'] = str(b[7])
            d['status'] = b[8]
            d['rssi'] = b[9]
           # if b[10] != None and b[10] != {}:
            #    d['service'] = ast.literal_eval(b[10])
           # else:
          #     d['service'] = "null"
            d['hop'] = b[10]
            d['flags'] = b[11]
            if b[1] == 'Ble':
                d['device_type'] = "低功耗蓝牙"
            else:
                d['device_type'] = '经典蓝牙'
            blueforjson.append(d)
        return jsonify({'blueInfo':blueforjson})
    except:
        import traceback
        traceback.print_exc()
        return jsonify({'tasks': 'Error: unable to Blue fetch data'})
    db.close()
# 蓝牙攻击检测信息
@app.route('/blueAttackScan',methods=['GET'])
@allow_cross_domain
def blueAttackScan():
    db = sqlconnect.connect()
    cur = db.cursor()
    sql = "select asset_mac,interface,detail,asset_type,evt_dev_time,status from (select distinct asset_mac,interface,detail,asset_type,evt_dev_time,status from blue_info) as tmp order by status desc;"
    try:
        cur.execute(sql)
        blue = cur.fetchall()
        blueforjson = []
        for b in blue:
            d = {}
            d['interface'] = b[1]
            d['asset_mac'] = b[0]
            if b[0] and blemessage.MAC_To_Conpany(b[0]):
                d['company'] = blemessage.MAC_To_Conpany(b[0])[0]
            else:
                d['company'] = '未知'
            # print type(d['company'])
            d['detail'] = b[2]
            d['asset_type'] = b[3]
            d['status'] = b[5]
            if b[1] == 'Ble':
                d['device_type'] = "低功耗蓝牙"
                if bluemessage.bleAttackByMac(b[0])[0][0] >0:
                    d['attackscan'] = bluemessage.bleAttackByMac(b[0])[0][0]
                    blueforjson.append(d)
            elif b[1] == 'Classic Blue':
                d['device_type'] = '经典蓝牙'
                if bluemessage.blueAttackByMac(b[0])[0][0] >0:
                    d['attackscan'] = bluemessage.blueAttackByMac(b[0])[0][0]
                    blueforjson.append(d)
        return jsonify({'blueInfo1':blueforjson})
    except:
        import traceback
        traceback.print_exc()
        return jsonify({'tasks': 'Error: unable to Blue fetch data'})
    db.close()
# 删除蓝牙信息
@app.route('/deleteblue/<string:id>', methods=['POST'])
@allow_cross_domain
def deleteblueInfo(id):
    db = sqlconnect.connect()
    cur = db.cursor()
    sql = "delete from blue_info where asset_mac = %s;"
    print id
    try:
        cur.execute(sql,[id])
        db.commit()
        return 'delete blue_info asset_mac successful', 200
    except:
       return jsonify({'tasks': 'Error: unable to delete Blue fetch data'})

    db.close()
# 蓝牙漏洞检测信息
@app.route('/blueleak', methods=['GET'])
@allow_cross_domain
def blue_Bug():
    if request.method == "GET":
        db = sqlconnect.connect()
        cur = db.cursor()
        sql = "select asset_mac,interface,detail,asset_type,evt_dev_time,status from (select distinct asset_mac,interface,detail,asset_type,evt_dev_time,status from blue_info) as tmp order by status desc;"
        try:
            cur.execute(sql)
            blue = cur.fetchall()
            db.close()
            blueforjson = []
            for b in blue:
                d = {}
                d['interface'] = b[1]
                d['asset_mac'] = b[0]
                if b[0] and blemessage.MAC_To_Conpany(b[0]):
                    d['company'] = blemessage.MAC_To_Conpany(b[0])[0]
                else:
                    d['company'] = '未知'
                # print type(d['company'])
                d['detail'] = b[2]
                d['asset_type'] = b[3]
                d['createtime'] = b[4]
                d['status'] = b[5]
                if b[1] == 'Ble':
                    d['device_type'] = "低功耗蓝牙"
                    if bluemessage.bluebugcount(b[0])[0][0] > 0:
                        d['attackscan'] = bluemessage.bluebugcount(b[0])[0][0]
                        blueforjson.append(d)
                elif b[1] == 'Classic Blue':
                    d['device_type'] = '经典蓝牙'
                    if bluemessage.bluebugcount(b[0])[0][0] > 0:
                        d['attackscan'] = bluemessage.bluebugcount(b[0])[0][0]
                        blueforjson.append(d)
            return jsonify({'blueInfo1': blueforjson})
        except:
            import traceback
            traceback.print_exc()
            return jsonify({'tasks': 'Error: unable to Blue fetch data'})

# 蓝牙漏洞详细的信息
@app.route('/blueleakmessage/<string:mac>', methods=['GET'])
@allow_cross_domain
def blue_leak_message(mac):
    if request.method == "GET":
        aa = mac.encode('utf-8').split(';')
        create_time = aa[1]
        asset_mac = aa[0]
        #print create_time,asset_mac
        db = sqlconnect.connect()
        cur = db.cursor()
        sql = "select b_message,create_time from b_leak_m where asset_mac = %s"
        cur.execute(sql,[asset_mac])
        leak = cur.fetchall()
        db.close()
        blue_leak_info = []
        for b in leak:
            d = {}
            d['create_time'] = b[1].strftime('%Y-%m-%d %H:%M:%S')
            d['b_message'] = b[0]

            bb=bluemessage.getblueleakmessage(b[0])[0]
            if bb != None:
                print bb
                d['description'] = bb[1]
                d['leak_name'] = bb[0]
                d['rank'] = bb[2]
                blue_leak_info.append(d)
            else:
                continue

        return jsonify({'blue_leak_info': blue_leak_info})
    else:
        return "error"


@app.route('/b_leak_m/<int:status>',  methods=['POST'])
@allow_cross_domain
def b_leak_m(status):
    db = sqlconnect.connect()
    cur = db.cursor()
    sql = "select asset_mac, b_message from b_leak_m where status=%s;"
    try:
        cur.execute(sql,[int(status)])
        b_leak_message = cur.fetchone()
        return jsonify({'b_leak_m':b_leak_message})
    except:
        import traceback
        traceback.print_exc()
        return jsonify({'tasks': 'Error: unable to Zigbee fetch data'})
    db.close()
# 谷歌手机漏洞泄露信息
@app.route('/leak_message/<string:asset_mac>', methods=['GET'])
@allow_cross_domain
def leak_message(asset_mac):
    db = sqlconnect.connect()
    cur = db.cursor()
    sql = "select b_message from b_leak_m where asset_mac=%s;"
    try:
        cur.execute(sql,[asset_mac])
        b_message1 = cur.fetchone()
        print b_message1[0].replace('\n','\n')

        b_message2 = b_message1[0].replace('\n','\n')

       # print type(b_message1[0])
       # print b_message1[0].repalce('/\n','</br>')
        return jsonify({'b_message':b_message2})
    except:
        return jsonify({'tasks':'ERROR:unable to leak_message'})
    db.close()

# ---------------------zigbee---------------------------
@app.route('/zigbeeinfo', methods=['GET'])
@allow_cross_domain
def zigbeeInfo():
    db = sqlconnect.connect()
    cur = db.cursor()
    sql = "select id, interface, addr, ip, create_time from zigbee_info"
    try:
        cur.execute(sql)
        zigbee = cur.fetchall()
        zigb = []
        for b in zigbee:
            d = {}
            d['id'] = b[0]
            d['interface'] = b[1]
            d['addr'] = b[2]
            d['ip'] = b[3]
            d['create_time'] = b[4].strftime('%Y-%m-%d %H:%M:%S')
            zigb.append(d)
        return jsonify({'zigbee': zigb})
    except:
        import traceback
        traceback.print_exc()
        return jsonify({'tasks': 'Error: unable to Zigbee fetch data'})
    db.close()
@app.route('/zigbeeA', methods=['GET'])
@allow_cross_domain
def zigbeeA():
    db = sqlconnect.connect()
    cur = db.cursor()
    sql = "select id,interface, client, RetraRate, ReceRate, xindao, zhibiao, create_time from zigbeeA"
    try:
        cur.execute(sql)
        zigbee = cur.fetchall()
        zigb = []
        for b in zigbee:
            d = {}
            d['id'] = b[0]
            d['interface'] = b[1]
            d['client'] = b[2]
            d['RetraRate'] = b[3]
            d['ReceRate'] = b[4]
            #print type(b[5])
            if b[5] == 0:
                d['xindao'] = '空闲'
            else:
                d['xindao'] = '忙碌'
            d['zhibiao'] = b[6]
            d['create_time'] = b[7].strftime('%Y-%m-%d %H:%M:%S')
            zigb.append(d)
        return jsonify({'zigbeeA': zigb})
    except:
        import traceback
        traceback.print_exc()
        return jsonify({'tasks': 'Error: unable to Zigbee fetch data'})
    db.close()
# --------------------wifi-------------------------------------
# wifi 设备
@app.route('/wifiinfo', methods=['GET'])
@allow_cross_domain
def wifiInfo():
    db = sqlconnect.connect()
    cur = db.cursor()
    sql = "select asset_mac,name,channel,encrpy,avg_signal,min_signal,max_signal,status from" \
          " (select distinct asset_mac,name,channel,encrpy,avg_signal,min_signal,max_signal,status,tag " \
          "from wifiDevice) as tmp where tag=1 order by status desc"
   # sql = "select asset_mac,id,name,channel,encrpy,avg_signal,min_signal,max_signal,create_time,status from wifiDevice order by create_time desc"
    try:
        cur.execute(sql)
        wifinfo1 = cur.fetchall()
        wifiinfo = []
        for b in wifinfo1:
            d = {}
         #   d['id'] = b[1]
            d['asset_mac'] = b[0].upper()
            #print b[1]
            #d['company'] =blemessage.MAC_To_Conpany(b[1])
            if b[0].upper() and blemessage.MAC_To_Conpany(b[0].upper()):
                d['company'] = blemessage.MAC_To_Conpany(b[0].upper())[0]
            else:
                d['company'] = '未知'
            #print d['company']
            d['wifiname'] = b[1]
            d['channel'] = b[2]
            if len(b[3]) == 2:
                d['encrpy'] = '未知'
            else:
                d['encrpy'] = re.sub('[\[\]\"]','',b[3])
               # for i in b[4]:
                 #   d['encrpy'] = ",".join(list(b[4]))
            d['avg_signal'] = b[4]
            d['min_signal'] = b[5]
            d['max_signal'] = b[6]
         #   d['create_time'] = b[8].strftime('%Y-%m-%d %H:%M:%S')
           # print b[9]
            if b[7] == 1:
                d['status'] = '在线'
            else:
                d['status'] = '离线'
            wifiinfo.append(d)
        return jsonify({'wifiinfo': wifiinfo})
    except:
        import traceback
        traceback.print_exc()
        return jsonify({'tasks': 'Error: unable to WIFI  fetch data'})
    db.close()
# 没有连接的信息
@app.route('/notAinfo', methods=['GET'])
@allow_cross_domain
def notAinfo():
    db = sqlconnect.connect()
    cur = db.cursor()
    sql = "select id, mac, create_time from not_A_Station"
    try:
        cur.execute(sql)
        wifinfo1 = cur.fetchall()
        notAinfo = []
        for b in wifinfo1:
            d = {}
            d['id'] = b[0]
            d['mac'] = b[1].upper()
            d['create_time'] = b[2].strftime('%Y-%m-%d %H:%M:%S')
            notAinfo.append(d)
        return jsonify({'notAinfo': notAinfo})
    except:
        import traceback
        traceback.print_exc()
        return jsonify({'tasks': 'Error: unable to Zigbee fetch data'})
    db.close()
# 已连接的信息，未连接ap 的设备
@app.route('/Ainfo', methods=['GET'])
@allow_cross_domain
def Ainfo():
    db = sqlconnect.connect()
    cur = db.cursor()
    cur2 = db.cursor()
    curnotAStation =db.cursor()
    sql = "select distinct AClient, Ap, Ap_name, wifi_A_Station.create_time,wifi_A_Station.id from wifi_A_Station,wifiDevice where wifi_A_Station.Ap_name = wifiDevice.name"
    sql2 ="select distinct wifi_A_Station.Ap,wifi_A_Station.Ap_name,wifiDevice.avg_signal from wifi_A_Station,wifiDevice where wifi_A_Station.Ap_name = wifiDevice.name"
    sql3 ="select distinct mac from not_A_Station"
    try:
        cur.execute(sql)
        cur2.execute(sql2)
        curnotAStation.execute(sql3)
        wifiname = cur2.fetchall()
        wifinfo1 = cur.fetchall()
        notAStation = curnotAStation.fetchall()
        Ainfo = []
        Binfo = []
        links=[]
        for b in wifinfo1: # 连接了ap的设备
            d = {}
            d['AClient'] = b[0].upper()
            d['Ap'] = b[1].upper()
            d['Ap_name'] = b[2].upper()
            d['create_time'] = b[3].strftime('%Y-%m-%d %H:%M:%S')
            d['id'] = b[4]
            Ainfo.append(d)
        for q in wifiname: # ap
            w ={}
            w['Ap'] = q[0].upper()
            w['Ap_name'] = q[1].upper()
            w['rssi'] = int(q[2][1:])

            Binfo.append(w)
        for c in notAStation: # 没有连接ap的设备
            x={}
            x['mac'] = c[0].upper()

            links.append(x)

        return jsonify({'Ainfo': Ainfo,'Binfo':Binfo,'notAStation':links})
    except:
        import traceback
        traceback.print_exc()
        return jsonify({'tasks': 'Error: unable to Zigbee fetch data'})
    db.close()
# 曾经连接的Wi-Fi记录
@app.route('/prob', methods=['GET'])
@allow_cross_domain
def prob():
    db = sqlconnect.connect()
    cur = db.cursor()
    sql = "select id, wifi_name,create_time,client from wifi_probSsid order by create_time desc"
    try:
        cur.execute(sql)
        wifinfo1 = cur.fetchall()
        probinfo = []
        for b in wifinfo1:
            d = {}
            d['id'] = b[0]
            d['wifiname'] = b[1]
            d['create_time'] = b[2].strftime('%Y-%m-%d %H:%M:%S')
            d['client'] = b[3]
            probinfo.append(d)
        return jsonify({'probinfo': probinfo})
    except:
        import traceback
        traceback.print_exc()
        return jsonify({'tasks': 'Error: unable to Zigbee fetch data'})
    db.close()
#  伪ap的信息
@app.route('/fakeap/<string:wifiname>', methods=['GET'])
@allow_cross_domain
def fakeap(wifiname):
    db = sqlconnect.connect()
    cur = db.cursor()
    sql = "select id, fake_M, fakename, create_time from wifi_fakeap where fakename = %s order by create_time desc limit 1"
    try:
        cur.execute(sql,[wifiname])
        fakeap = cur.fetchall()
        fakeaplist = []
        for b in fakeap:
            d = {}
            d['id'] = b[0]
            d['fakeM'] = b[1]
            d['fakename'] = b[2]
            d['create_time'] = b[3].strftime('%Y-%m-%d %H:%M:%S')
        fakeaplist.append(d)
        return jsonify({'fakeaplist': fakeaplist})
    except:
        import traceback
        traceback.print_exc()
        return jsonify({'tasks': 'Error: unable to Zigbee fetch data'})
    db.close()
# 根据Mac地址获取ap的攻击监测信息
@app.route('/wifiDossmessage/<string:mac>', methods=['GET'])
@allow_cross_domain
def wifidossmessage(mac):
    db = sqlconnect.connect()
    cur = db.cursor()
    cur2 = db.cursor()
    sql = "select id, Dos_type, create_time, victim from wifi_Doss where victim = %s order by create_time desc"
  #  print type(mac.split(';')[0].encode('utf-8'))
    # Ap的 mac 地址
    ApMac = mac.split(';')[0].encode('utf-8')
    # Ap的 名称
    wifiname1 = mac.split(';')[1].encode('utf-8')
   # print wifimessage.findProbeReqAtkByApName(wifiname1)
    doslist = []

    attackdic = {'associationAttack': '关联攻击',
                 'AssociationAttack':'关联攻击',
         'DisassociationAttack': '取消关联攻击',
         'disassociationAttack': '取消关联攻击',
         'DataReplyAttack': 'QoS数据重放攻击',
         'proberequAttack': '探测请求攻击',
         'ProbeReqAtk':'探测请求攻击',
         'authAttackdic': 'Auth攻击',
         'authAttack': 'Auth攻击',
         'deauthAttackdic': 'Deauth攻击',
         'BeaconFloodAttack': 'Beancon泛洪攻击'
         }
    # 判断是否是探测请求攻击
    if wifimessage.findProbeReqAtkByApName(wifiname1)[0][0] >1:
            try:
                cur.execute(sql,[wifiname1])
                dos1 = cur.fetchall()
                for b in dos1:
                    d = {}
                    d['id'] = b[0]
                    d['Dos_type'] = attackdic[b[1]]
                   # print b[1]
                    d['create_time'] = b[2].strftime('%Y-%m-%d %H:%M:%S')
                    d['victim'] = ApMac  # 被攻击的设备Mac
                    doslist.append(d)
                #return jsonify({'doslist1': doslist})
            except:
                pass
    if wifimessage.findBeaconAttackfromwifiDoss()[0][0] >0:
        beaconmessage = wifimessage.finBeaconAttack()
        for b in beaconmessage:
            d ={}
            d['id'] = b[0]
            d['Dos_type'] = attackdic[b[1]]
            d['create_time'] = b[2].strftime('%Y-%m-%d %H:%M:%S')
            d['victim'] = ApMac  # 被攻击的设备Mac
            doslist.append(d)
    try:
        cur2.execute(sql,[ApMac.lower()])
        dos = cur2.fetchall()
        #print dos
        if len(dos) >0:
            #doslist = []
            for b in dos:
                d = {}
                d['id'] = b[0]
                d['Dos_type'] = attackdic[b[1]]
                d['create_time'] = b[2].strftime('%Y-%m-%d %H:%M:%S')
                d['victim'] = b[3].upper()  # 被攻击的设备Mac
                doslist.append(d)
           # print doslist
            return jsonify({'doslist1': doslist})
        else:
            return jsonify({'doslist1': doslist})
    except:
        import traceback
        traceback.print_exc()
        return jsonify({'tasks': 'Error: unable to wifidoss fetch data'})
    db.close()
# Ap攻击监测表   攻击检测和伪Ap监测
@app.route('/wifiDoss1', methods=['GET'])
@allow_cross_domain
def wifidoss1():
    db = sqlconnect.connect()
    cur = db.cursor()
    sql = "select asset_mac,name,status from (select distinct asset_mac,name,status from wifiDevice) as tam order by status desc;"
    try:
        cur.execute(sql)
        wifinfo1 = cur.fetchall()
        wifiinfo = []
        for b in wifinfo1:
            d = {}
            d['asset_mac'] = b[0].upper()
            if b[1].upper() and blemessage.MAC_To_Conpany(b[0].upper()):
                d['company'] = blemessage.MAC_To_Conpany(b[0].upper())[0]
            else:
                d['company'] = '未知'
            d['wifiname'] = b[1]   # AP 的名字
            if b[2] == 1:
                d['status'] = '在线'
            else:
                d['status'] = '离线'
            # print wifimessage.findProbeReqAtkByApName(b[1])[0][0]
            if wifimessage.findProbeReqAtkByApName(b[1])[0][0] > 0:
                if wifimessage.wifiDosscount(b[0])[0][0] > 0 and wifimessage.wifiFakeAp(b[1]):
                     d['weiap'] = len(wifimessage.wifiFakeAp(b[1]))
                     d['wifidoss'] = wifimessage.wifiDosscount(b[0])[0][0] + wifimessage.findProbeReqAtkByApName(b[1])[0][0] + wifimessage.findBeaconAttackfromwifiDoss()[0][0]
                     wifiinfo.append(d)
                elif wifimessage.wifiDosscount(b[0])[0][0] > 0 and len(wifimessage.wifiFakeAp(b[1])) == 0:
                        d['weiap'] = 0
                        d['wifidoss'] = wifimessage.wifiDosscount(b[0])[0][0] + wifimessage.findProbeReqAtkByApName(b[1])[0][0] + wifimessage.findBeaconAttackfromwifiDoss()[0][0]
                        wifiinfo.append(d)
                elif wifimessage.wifiDosscount(b[0])[0][0] == 0 and wifimessage.wifiFakeAp(b[1]):
                    d['weiap'] = len(wifimessage.wifiFakeAp(b[1]))
                    d['wifidoss'] = 0 + wifimessage.findBeaconAttackfromwifiDoss()[0][0]
                    wifiinfo.append(d)
                elif wifimessage.wifiDosscount(b[0])[0][0] == 0 and len(wifimessage.wifiFakeAp(b[1])) ==0:
                    d['weiap'] = 0
                    d['wifidoss'] = wifimessage.findProbeReqAtkByApName(b[1])[0][0] + wifimessage.findBeaconAttackfromwifiDoss()[0][0]
                    wifiinfo.append(d)
            else:
                if wifimessage.wifiDosscount(b[0])[0][0] > 0 and wifimessage.wifiFakeAp(b[1]):
                     d['weiap'] = len(wifimessage.wifiFakeAp(b[1]))
                     d['wifidoss'] = wifimessage.wifiDosscount(b[0])[0][0] + wifimessage.findBeaconAttackfromwifiDoss()[0][0]
                     wifiinfo.append(d)
                elif wifimessage.wifiDosscount(b[0])[0][0] > 0 and len(wifimessage.wifiFakeAp(b[1])) == 0:
                        d['weiap'] = 0
                        d['wifidoss'] = wifimessage.wifiDosscount(b[0])[0][0] + wifimessage.findBeaconAttackfromwifiDoss()[0][0]
                        wifiinfo.append(d)
                elif wifimessage.wifiDosscount(b[0])[0][0] == 0 and wifimessage.wifiFakeAp(b[1]):
                    d['weiap'] = len(wifimessage.wifiFakeAp(b[1]))
                    d['wifidoss'] = 0 + wifimessage.findBeaconAttackfromwifiDoss()[0][0]
                    wifiinfo.append(d)
        return jsonify({'wifiinfo1': wifiinfo})
    except:
        import traceback
        traceback.print_exc()
        return jsonify({'tasks': 'Error: unable to WIFI  fetch data'})
    db.close()
'''
# beacon攻击监测
@app.route('/wifiBeaconAttack', methods=['GET'])
@allow_cross_domain
def wifiBeaconAttack():
    db = sqlconnect.connect()
    cur = db.cursor()
    sql = "select victim from wifi_Doss where Dos_type= 'BeaconFloodAttack' order by create_time limit 1;"
    try:
        cur.execute(sql)
        beaconAttack = cur.fetchall()
       # print beaconAttack[0][0]
        if beaconAttack[0][0] == 'FoundBeaconAttack':
            message = '当前AP环境中正在发生beacon攻击！！！'
        else:
            message = '无'
        return jsonify({'beaconAttack':message})
    except:
        import traceback
        traceback.print_exc()
        return jsonify({'beaconAttack': '无'})
    db.close()
'''
# Wi-Fi漏洞检测
@app.route('/routerleak', methods=['GET'])
@allow_cross_domain
def router_leak():
    db=sqlconnect.connect()
    cur = db.cursor()
    sql = "select wifiDevice.asset_mac,router_leak.create_time,router_leak.leak_message,wifiDevice.name,wifiDevice.status from wifiDevice inner join router_leak on wifiDevice.name = router_leak.asset_mac;"
    try:
        cur.execute(sql)
        routerleak = cur.fetchall()
        routerinfo = []
        for b in routerleak:
            d = {}
            d['asset_mac'] = b[0].upper()
            if b[3].upper() and blemessage.MAC_To_Conpany(b[0].upper()):
                d['company'] = blemessage.MAC_To_Conpany(b[0].upper())[0]
            else:
                d['company'] = '未知'
            d['wifiname'] = b[3]  # AP 的名字
            if b[4] == 1:
                d['status'] = '在线'
            else:
                d['status'] = '离线'
            leak = b[2].split(";")
            d['leakcount'] = len(leak)
            routerinfo.append(d)
        return jsonify({'routerinfo': routerinfo})
    except:
        import traceback
        traceback.print_exc()
        return jsonify({'tasks': 'Error: unable to WIFI  fetch data'})
    db.close()
# 路由器漏洞信息-----
@app.route('/routerleakmessage/<string:mac>', methods=['GET'])
@allow_cross_domain
def routerleakmessage(mac):
    db = sqlconnect.connect()
    cur = db.cursor()
    sql = "select leak_message,create_time from router_leak where asset_mac = %s"
    #  print type(mac.split(';')[0].encode('utf-8'))
    # Ap的 mac 地址
    wifiname = mac.encode('utf-8')
    # Ap的 名称

    cur.execute(sql, [wifiname])
    message = cur.fetchall()[0]
    leakinfo = []
    for b in message[0].split(";"):
        d ={}
        d['mac'] = wifiname
        # 路由漏洞名称
        routerleak = b.split('/')[-1]
        print routerleak
        d['leakmessage'] = routerleak
        for i in  wifimessage.getmessageFronRouterLibraryByName(routerleak):
            print i
            d['leak_name'] = i[0]
            d['rank'] = i[1]
            d['description'] = i[2]
            d['device'] = i[3]
            d['create_time'] = message[1].strftime('%Y-%m-%d %H:%M:%S')
            leakinfo.append(d)
  #  print mac,message
    return jsonify({'message':leakinfo})

# 设备总览数据<<<<
# 设备总览--设备识别
@app.route('/device_for_home',methods=['GET'])
@allow_cross_domain
def deviceforHome():
    db = sqlconnect.connect()
    cur = db.cursor()
    sql = "select count(distinct blue.asset_mac) as blue,count(distinct if (blue.status =1,blue.asset_mac,null)) as blueon," \
          "count( distinct if(blue.status =0,blue.asset_mac,null)) as blueoff,count(distinct wifi.asset_mac) as wifis," \
          "count(distinct if(wifi.status = 1,wifi.asset_mac,null)) as wifionline,count(distinct if(wifi.status =0,wifi.asset_mac,null))" \
          " as wifioff from blue_info as blue,wifiDevice as wifi;"
    try:
        cur.execute(sql)
        device_for_home_top = cur.fetchall()[0]
        d = {}
        d['blue'] = device_for_home_top[0]
        d['blueonline'] = device_for_home_top[1]
        d['blueoff'] = device_for_home_top[2]
        d['wifi'] =device_for_home_top[3]
        d['wifionline'] = device_for_home_top[4]
        d['wifioff'] = device_for_home_top[5]
        d['device'] = device_for_home_top[0] + device_for_home_top[3]
       # print device_for_home_top
        return jsonify({'deviceforhome':d})
    except:
        return jsonify({'ss':'无'})
    db.close()

@app.route('/leak_for_home_middle', methods=['GET'])
@allow_cross_domain
def deviceforLeak():
    db = sqlconnect.connect()
    cur = db.cursor()
    sql = "select count(distinct blue.asset_mac)+count(distinct wifi.asset_mac) as device," \
          "count(distinct blue.id) as leak from (select id,asset_mac,b_message from b_leak_m) " \
          "as blue, router_leak as wifi;"
    cur2 = db.cursor()
    sql2 = "select leak_message from router_leak;"
    try:
        cur2.execute(sql2)
        wifileak = cur2.fetchall()
        routerleak = 0
        for b in wifileak:
            leak = b[0].split(";")
            routerleak = routerleak + len(leak)
        cur.execute(sql)
        leak = cur.fetchall()[0]
        deviceforleak = {}
        deviceforleak['device'] = leak[0]
        deviceforleak['leak'] = leak[1]+routerleak
        deviceforleak['routerleak'] = routerleak
        deviceforleak['blueleak'] = leak[1]
        deviceforleak['zigbeeleak'] = 1
        return jsonify({'deviceforleak': deviceforleak})
    except:
        pass
        return ''
    db.close()


@app.route('/attack_for_home_bottom', methods=['GET'])
@allow_cross_domain
def deviceforAttack():
    db = sqlconnect.connect()
    cur = db.cursor()
    sql = "select count(distinct blue.mac)+count(distinct ble.slave) as blue," \
          " count(distinct blue.id)+count(distinct ble.id) as blueAttack, " \
          " count(distinct wifi.victim) as wifis,count(distinct wifi.id) as" \
          " wifiAttack from blueAttackScan as blue,bleAttackScan as ble," \
          "(select id,victim from wifi_Doss where victim <>'ff:ff:ff:ff:ff:ff') as wifi;"
    try:
        cur.execute(sql)
        attack_for_home_bottom = cur.fetchall()[0]
        d = {}
        d['blue'] = attack_for_home_bottom[0]
        d['blueAttack'] = attack_for_home_bottom[1]
        d['wifi'] = attack_for_home_bottom[2]
        d['wifiAttack'] = attack_for_home_bottom[3]
        #
        return jsonify({'deviceforAttack':d})
    except:
        return jsonify({'deviceforAttack':'无'})
    db.close()




if __name__ == '__main__':
    app.run(debug=True)
